package service;

import core.ByteBuf;
import http.HttpRequest;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

public class ParameterHandler {
    /**
     * 解析请求参数
     */
    public static Object[] resolveRequestParam(HttpRequest httpRequest, Method targetMethod) {
        Parameter[] parameters = targetMethod.getParameters();
        Object[] realParams = new Object[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            System.out.println(parameter);
            // 参数分为param和body类型
            if (parameter.isAnnotationPresent(RequestBody.class)) {
                Class<?> type = parameter.getType();
                ByteBuf content = httpRequest.byteBuf;
                String jsonString = content.toString(StandardCharsets.UTF_8);
                System.out.println(jsonString);
                realParams[i] = FastJsonUtils.getJsonToBean(jsonString, type);
            } else if (parameter.isAnnotationPresent(RequestParam.class)) {
                RequestParam annotation = parameter.getAnnotation(RequestParam.class);
                String value = annotation.value();
                QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httpRequest.uri);
                Map<String, List<String>> params = queryStringDecoder.parameters();
                List<String> values = params.get(value);
                if (!values.isEmpty()) {
                    Class<?> type = parameter.getType();
                    if (type == String.class) {
                        realParams[i] = values.get(0);
                    }
                    if (type == Integer.class || type == int.class) {
                        realParams[i] = Integer.parseInt(values.get(0));
                    }
                    if (type == Double.class || type == double.class) {
                        realParams[i] = Double.parseDouble(values.get(0));
                    }
                }
            }
        }
        return realParams;
    }
}
